#include "s_common_message.h"
#include "h_stm32_hal_defines.h"
#include <stdio.h>
#include <string.h>

static s_message_t s_message_head;

void s_common_message_init(void)
{
	s_message_head.next = NULL;
}

s_common_state s_common_message_add(const unsigned char *cmd, unsigned short len, void *callBack)
{
	s_message_t *tail_msg = &s_message_head;

	if(!len) {
		return s_common_para_illegal;
	}

	while(tail_msg->next != NULL) {
		if(!memcmp(tail_msg->next->message, cmd, len)) {
			return s_common_existed;
		}
		tail_msg = tail_msg->next;
	}

	tail_msg->next = (s_message_t *)H_STM32_MALLOC(sizeof(s_message_t));


	if(NULL == tail_msg->next) {
		return s_common_malloc_failed;
	}

	tail_msg->next->message = (unsigned char *)H_STM32_MALLOC(sizeof(unsigned char) * len);
	if(NULL == tail_msg->next->message) {
		return s_common_malloc_failed;
	}

	memcpy(tail_msg->next->message, cmd, len);


	tail_msg->next->message_len = len;
	tail_msg->next->callBack = callBack;
	tail_msg->next->next = NULL;

	return s_common_state_ok;
}

extern UART_HandleTypeDef huart1;

s_common_state s_common_message_head(const unsigned char *cmd, unsigned short len)
{
	s_message_t *tail_msg = s_message_head.next;

	if(!len) {
		return s_common_para_illegal;
	}

	while(tail_msg != NULL) {
		if(!memcmp(tail_msg->message, cmd, tail_msg->message_len)) {
			break;
		}
		tail_msg = tail_msg->next;
	}

	if(NULL == tail_msg) {
		// printf("not found\r\n");
		// printf("%s\n", cmd);

		// HAL_UART_Transmit(&huart1 , cmd, len, 0xFF);
		// printf("%.*s\n", len, cmd);
		

		return s_common_notExisted;
	}

	tail_msg->callBack(&cmd[tail_msg->message_len], len - tail_msg->message_len);

	return s_common_state_ok;

}

